import React, { Component } from 'react'
import Grid from '../../components/Grid'
import {BannerList} from '../../components/SwiperList/BannerList'
import {RankingList} from '../../components/SwiperList/RankingList'
import PopupSongList from '../../components/Popup/PopupSongList'
import {_getTopList,_getPlayListDetail,_getPersonalized}from '../../api/recommend'
import { Arrow } from '@react-vant/icons'
import { Flex, Skeleton, NoticeBar } from 'react-vant';
import './index.scss'
import {connect} from 'react-redux'
import { useNavigate} from 'react-router-dom'
import { changeMusicSrcAsync,changeMusicControls,changeMusicNode,changePlayOrder,changeMusicListAsync,changeMusicCurrentDetail} from '../../store/actions/music'

export const withNavigation = (Component) => {
  return (props) => <Component {...props} navigate={useNavigate()} />;
};
 class Home extends Component {
  state = {
    topList:[],
    rankingLoading:true,
    songListVisible:false, //首页歌单列表Popup开关
  }
  componentDidMount(){
    if(!this.props.musicList[0]){ 
      this.getPersonalized()
    }
    this.getTopListDetails()
  }

  getPersonalized=()=>{
    _getPersonalized().then(res=>{
      var index = this.getRandomIntInclusive(0, res.result.length-1);
      index = parseInt(index, 10);
      this.props.changeMusicListAsync( res.result[index].id)
    })
  }
  getRandomIntInclusive=(min, max)=> {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min; //含最大值，含最小值 
  }  

  getTopListDetails= async()=>{
    const res = await _getTopList()
    const list = res.list.slice(0,5)
    list.map(async(item,index)=>{
      const rankingRes = await _getPlayListDetail(item.id)
      let rankingObj = {
        name:rankingRes.playlist.name,
        id:rankingRes.playlist.id,
        tracks:rankingRes.playlist.tracks.slice(0,3),
      }
      this.setState({
        topList:[...this.state.topList,rankingObj]
      },()=>{
          this.setState({
            rankingLoading:false
          })
      })
    })  
  }
  closePopupSongList=()=>{
    this.setState({
      songListVisible:false
    })
  }
  playControls=(e)=>{
    e.stopPropagation();
    e.nativeEvent.stopImmediatePropagation();
    let flag = this.props.musicControls
    this.props.changeMusicControls(!flag)
    flag? this.props.musicNode.play() : this.props.musicNode.pause()
  }
  goPlaySong=()=>{
    this.props.navigate("/playsong")
  }
  goAllTopList=()=>{
    this.props.navigate("/alltoplist")
  }
  render() {
    const {musicSrc,musicControls,musicCurrentDetail} = this.props
    return (
      <div className="home">
        <BannerList/>
        <div className="grids">
          <Grid/>
        </div>
        <div className='ranking'>
          <Cells name="排行榜" path={()=>this.goAllTopList()} />
          <Skeleton avatar  loading={this.state.rankingLoading}>
            <RankingList topList={this.state.topList}/>
          </Skeleton>
        </div>
        <Flex className='music_controls' onClick={this.goPlaySong}>
          <div className='space'/>
          <Flex align='center' justify='between' className='controls'>
            <img src={musicCurrentDetail.al ? musicCurrentDetail.al.picUrl+'?param=56y56': 'http://p3.music.126.net/xqLdMAbT8jLolXZBsQl-zA==/17660355765482772.jpg?param=56y56'}/>
            <NoticeBar className='notice_bar' speed={40}
              scrollable text={musicSrc.src?musicCurrentDetail.name+' - '+ 
                (musicCurrentDetail.ar || []).map(itm=>{return itm.name}):'暂无歌曲在播放~~~'} />
            <div>
              <span className={['iconfont', (musicSrc && musicControls===false)?'icon-bofang1':'icon-bofang2'].join(' ')} onClick={(e)=>this.playControls(e)}/>
              <span className='iconfont icon-24gf-playlistMusic4' onClick={(e)=>{e.stopPropagation();e.nativeEvent.stopImmediatePropagation();this.setState({songListVisible:true})}}/>
            </div>
          </Flex>
          <div className='space'/>
        </Flex>
        <PopupSongList songListVisible={this.state.songListVisible} closePopupSongList={this.closePopupSongList}/>
      </div>
    )
  }
}



const Cells = props=> {
  return (
    <div className='cell_'>
      <h3>{props.name}</h3>
      <div onClick={()=>props.path()}>
        <span>更多</span>
        <Arrow  fontSize='0.9rem'/>
      </div>
    </div>
  )
}
export default withNavigation(connect(
  state =>({
    musicSrc:state.musicSrc,
    musicControls:state.musicControls,
    musicCurrentDetail:state.musicCurrentDetail,
    musicNode:state.musicNode,
    playOrder:state.playOrder,
    musicList:state.musicList,
  }),{
    changeMusicSrcAsync,
    changeMusicListAsync,
    changeMusicControls,
    changeMusicCurrentDetail,
    changeMusicNode,
    changePlayOrder
  })(Home));


